package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.pojo.system.LoginLog;
import com.qingcheng.service.system.LoginLogService;
import com.qingcheng.util.WebUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 登录成功处理器(登录成功干嘛)
 */
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler{

    @Reference
    private LoginLogService loginLogService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        //System.out.println("success------------------------------>");

        String name = authentication.getName();//登录名
        String remoteAddr = httpServletRequest.getRemoteAddr();//ip
        String browserName = null;//浏览器名称
        String city = null;
        try {
            city = WebUtil.getCityByIP(remoteAddr);//登录地
            browserName = WebUtil.getBrowserName(httpServletRequest.getHeader("user-agent"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        //组装登录日志
        LoginLog loginLog = new LoginLog();
        loginLog.setLoginName(name);
        loginLog.setIp(remoteAddr);
        loginLog.setBrowserName(browserName);
        loginLog.setLoginTime(new Date());

        //保存登录日志
        loginLogService.add(loginLog);

        //转发请求
        httpServletRequest.getRequestDispatcher("/main.html").forward(httpServletRequest,httpServletResponse);
    }
}
